package com.mfc.ctrl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mfc.cons.Sys;
import com.mfc.entity.Medicine;
import com.mfc.service.MedicineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/jsp/ingredients")
public class InIngredientsController {

	@Autowired
	private MedicineService medicineService;




	@RequestMapping("/page")
	public String page(@RequestParam(value="pageNo",defaultValue="1")int pageNo
			, Medicine o, Model model) {
		PageHelper.startPage(pageNo,Sys.pageSize," medicineId desc ");
		List<Medicine> li = medicineService.list(o);
		PageInfo<Medicine> pageInfo=new PageInfo<Medicine>(li, Sys.pageSize);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("o", o);
		return Sys.jsp+"/ingredients_page";
	}


	@RequestMapping("/toedit")
	public String toedit(@RequestParam(value="pageNo",defaultValue="1")int pageNo
			,Medicine o,Model model) {
		if(o.getMedicineId()!=null){
			o = medicineService.list(o).get(0);
			model.addAttribute("o", o);
		}
		System.out.println(o);
		model.addAttribute("pageNo", pageNo);
		return Sys.jsp+"/ingredients_add";
	}

	@RequestMapping("/save")
	public String save(@RequestParam(value="pageNo",defaultValue="1")int pageNo
			,Medicine o,Model model) {
		if(o.getMedicineId()!=null){
			medicineService.update(o);
		}else{
			medicineService.insert(o);
		}
		return "redirect:/"+Sys.jsp+"/ingredients/page?pageNo="+pageNo;
	}




	@RequestMapping("/del")
	public String del(@RequestParam(value="pageNo",defaultValue="1")int pageNo
			,Medicine o,Model model) {
		try {
			medicineService.delete(o.getMedicineId());
		} catch (Exception e) {
			model.addAttribute("msg", "删除失败");
			return "forward:/"+Sys.jsp+"/ingredients/page?pageNo="+pageNo;
		}
		return "redirect:/"+Sys.jsp+"/ingredients/page?pageNo="+pageNo;
	}
	@ResponseBody
	@RequestMapping("/getpage")
	public Object getpage(@RequestParam(value="pageNo",defaultValue="1")int pageNo
			, Medicine o, Model model) {
		PageHelper.startPage(pageNo,Sys.pageSize," medicineId desc ");
		List<Medicine> li = medicineService.list(o);
		PageInfo<Medicine> pageInfo=new PageInfo<Medicine>(li, Sys.pageSize);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("o", o);
		return pageInfo;
	}
}
